package com.xyz.eventoper;

import com.free.common.vo.ResultModel;
import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.ext.spring.context.AppContext;
import com.xyz.blockqueue.EventQueue;
import com.xyz.blockqueue.QueueModel;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class EventOperContext {

    private static final FreeLogger LOG = FreeLoggerFactory.getLogger(EventOperContext.class);

    private Map<String, IEventOper> deals = new HashMap<String, IEventOper>();

    public void init(){
        Map<String, IEventOper> beans = AppContext.getContext().getBeansOfType(IEventOper.class);
        beans.values().forEach(t -> {
            AbstractEventOper oper = (AbstractEventOper)t;
            deals.put(oper.getEventType().getType(), oper);
        });
    }

    public void putQueue(QueueModel modelInfo){
        try{
            EventQueue.getInstance().put(modelInfo);
        }catch (Exception ex){
            LOG.info("信息放入队列时，发生异常{}", ex);
        }
    }

    public ResultModel executeOper(QueueModel modelInfo){
        IEventOper oper = deals.get(modelInfo.getEventType().getType());
        if(oper != null){
            try{
                return   oper.operate(modelInfo);
            }catch (Exception ex){
                LOG.info("{}[{}],处理的时候发生异常",modelInfo.getEventType(),modelInfo.getCustomerInfo());
                return ResultModel.failure();
            }
        }else{
            LOG.info("{}[{}],处理的时候发生异常",modelInfo.getEventType(),modelInfo.getCustomerInfo());
            return ResultModel.failure();
        }
    }

}
